<template>
  <div>
    <el-container>
      <el-header>
        <span>矩阵运算计算器</span>
        <div style="margin-left: 20px; display: flex; align-items: center;">
          <el-select 
            v-model="selectedOperation" 
            placeholder="选择运算类型" 
            style="width: 200px"
            size="small"
          >
            <el-option label="矩阵加法" value="add"></el-option>
            <el-option label="矩阵减法" value="subtract"></el-option>
            <el-option label="矩阵乘法" value="multiply"></el-option>
            <el-option label="矩阵转置" value="transpose"></el-option>
            <el-option label="矩阵行列式" value="determinant"></el-option>
            <el-option label="矩阵求逆" value="inverse"></el-option>
          </el-select>
          
          <el-button 
            type="primary" 
            style="margin-left: 10px"
            @click="calculate"
            :disabled="!canCalculate"
            size="small"
          >
            计算
          </el-button>
        </div>
      </el-header>

      <el-main>
        <div class="matrix-container">
          <!-- 矩阵A -->
          <div class="matrix-input">
            <h3>矩阵A</h3>
            <div class="matrix-dimension-controls">
              <el-input-number 
                v-model="rowsA" 
                :min="1" 
                :max="10" 
                size="small"
                style="width: 80px;"
                controls-position="right"
                @change="updateMatrixADimensions"
              ></el-input-number>
              <span style="margin: 0 5px;">×</span>
              <el-input-number 
                v-model="colsA" 
                :min="1" 
                :max="10" 
                size="small"
                style="width: 80px;"
                controls-position="right"
                @change="updateMatrixADimensions"
              ></el-input-number>
              <el-button 
                @click="randomizeMatrix('A')"
                size="small"
                style="margin-left: 10px;"
              >
                随机生成
              </el-button>
            </div>
            <div class="matrix-grid">
              <div v-for="(row, i) in matrixA" :key="'a-row-'+i" class="matrix-row">
                <el-input 
                  v-for="(col, j) in row" 
                  :key="'a-'+i+'-'+j"
                  v-model.number="matrixA[i][j]"
                  type="number"
                  size="small"
                  style="width: 80px; margin: 2px;"
                ></el-input>
              </div>
            </div>
          </div>
          
          <!-- 矩阵B (当需要两个矩阵时显示) -->
          <div class="matrix-input" v-if="needsTwoMatrices">
            <h3>矩阵B</h3>
            <div class="matrix-dimension-controls">
              <el-input-number 
                v-model="rowsB" 
                :min="1" 
                :max="10" 
                size="small"
                style="width: 80px;"
                controls-position="right"
                @change="updateMatrixBDimensions"
              ></el-input-number>
              <span style="margin: 0 5px;">×</span>
              <el-input-number 
                v-model="colsB" 
                :min="1" 
                :max="10" 
                size="small"
                style="width: 80px;"
                controls-position="right"
                @change="updateMatrixBDimensions"
              ></el-input-number>
              <el-button 
                @click="randomizeMatrix('B')"
                size="small"
                style="margin-left: 10px;"
              >
                随机生成
              </el-button>
            </div>
            <div class="matrix-grid">
              <div v-for="(row, i) in matrixB" :key="'b-row-'+i" class="matrix-row">
                <el-input 
                  v-for="(col, j) in row" 
                  :key="'b-'+i+'-'+j"
                  v-model.number="matrixB[i][j]"
                  type="number"
                  size="small"
                  style="width: 80px; margin: 2px;"
                ></el-input>
              </div>
            </div>
          </div>
        <!-- 添加错误提示区域 -->
      <div v-if="errorMessage" class="error-message">
        <el-alert
          :title="errorMessage"
          type="error"
          show-icon
          :closable="false"
        ></el-alert>
      </div>
          <!-- 结果矩阵 -->
          <div class="matrix-result" v-if="resultMatrix || scalarResult !== null">
            <h3>结果</h3>
            <div class="result-display" v-if="resultMatrix">
              <div v-for="(row, i) in resultMatrix" :key="'result-row-'+i" class="matrix-row">
                <div 
                  v-for="(col, j) in row" 
                  :key="'result-'+i+'-'+j"
                  class="matrix-cell"
                >
                  {{ formatNumber(col) }}
                </div>
              </div>
            </div>
            <div v-if="scalarResult !== null" class="scalar-result">
              结果: {{ formatNumber(scalarResult) }}
            </div>
          </div>
        </div>
      </el-main>

      <el-footer>
        <div v-if="history.length > 0">
          <p>计算历史：</p>
          <el-table :data="history" style="width: 100%" height="150" size="small">
            <el-table-column prop="operation" label="运算类型" width="120"></el-table-column>
            <el-table-column prop="expression" label="表达式"></el-table-column>
            <el-table-column prop="result" label="结果"></el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button @click="useHistory(scope.row)" size="mini">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedOperation: 'add',
      rowsA: 2,
      colsA: 2,
      rowsB: 2,
      colsB: 2,
      matrixA: this.createMatrix(2, 2),
      matrixB: this.createMatrix(2, 2),
      resultMatrix: null,
      scalarResult: null,
      history: [],
      errorMessage: '',
      decimalPlaces: 4
    };
  },
  computed: {
    needsTwoMatrices() {
      return ['add', 'subtract', 'multiply'].includes(this.selectedOperation);
    },
    canCalculate() {
      if (this.selectedOperation === 'transpose' || 
          this.selectedOperation === 'determinant' || 
          this.selectedOperation === 'inverse') {
        return this.matrixA.length > 0;
      }
      return this.matrixA.length > 0 && this.matrixB.length > 0;
    }
  },
  methods: {
    createMatrix(rows, cols) {
    this.errorMessage = '';
      return Array(rows).fill().map(() => Array(cols).fill(0));
    },
    
    updateMatrixADimensions() {
      this.errorMessage = '';
      this.matrixA = this.createMatrix(this.rowsA, this.colsA);
      this.clearResult();
    },
    
    updateMatrixBDimensions() {
      this.errorMessage = '';
      this.matrixB = this.createMatrix(this.rowsB, this.colsB);
      this.clearResult();
    },
    
    randomizeMatrix(matrix) {
      this.errorMessage = '';
      const target = matrix === 'A' ? this.matrixA : this.matrixB;
      // 创建新数组确保响应式更新
      const newMatrix = [];
      for (let i = 0; i < target.length; i++) {
        newMatrix[i] = [];
        for (let j = 0; j < target[i].length; j++) {
          newMatrix[i][j] = Math.floor(Math.random() * 21) - 10;
        }
      }
      
      if (matrix === 'A') {
        this.matrixA = newMatrix;
      } else {
        this.matrixB = newMatrix;
      }
      this.clearResult();
    },
    
    clearResult() {
      this.resultMatrix = null;
      this.scalarResult = null;
    },
    
    formatNumber(num) {
      this.errorMessage = '';
      if (num === null || num === undefined) return '';
      // 如果是整数，显示为整数；否则保留4位小数
      return Number.isInteger(num) ? num : num.toFixed(this.decimalPlaces);
    },
    
 async calculate() {
      // 先清除之前的错误信息
      this.errorMessage = '';
      
      // 检查矩阵乘法维度
      if (this.selectedOperation === 'multiply') {
        if (this.colsA !== this.rowsB) {
          this.errorMessage = `矩阵乘法要求A的列数等于B的行数，当前A是${this.rowsA}×${this.colsA}，B是${this.rowsB}×${this.colsB}`;
          this.clearResult();
          return;
        }
      }
      
      // 检查其他运算的维度要求
      if (this.selectedOperation === 'add' || this.selectedOperation === 'subtract') {
        if (this.rowsA !== this.rowsB || this.colsA !== this.colsB) {
          this.errorMessage = `${this.selectedOperation === 'add' ? '加法' : '减法'}要求矩阵维度相同，当前A是${this.rowsA}×${this.colsA}，B是${this.rowsB}×${this.colsB}`;
          this.clearResult();
          return;
        }
      }
      
      // 检查行列式和逆矩阵要求方阵
      if (this.selectedOperation === 'determinant' || this.selectedOperation === 'inverse') {
        if (this.rowsA !== this.colsA) {
          this.errorMessage = `${this.selectedOperation === 'determinant' ? '行列式' : '逆矩阵'}计算要求矩阵为方阵，当前A是${this.rowsA}×${this.colsA}`;
          this.clearResult();
          return;
        }
      }
      
      // 原有计算逻辑
      const requestData = {
        operation: this.selectedOperation,
        matrixA: this.matrixA,
        rowsA: this.rowsA,
        colsA: this.colsA,
        matrixB: this.needsTwoMatrices ? this.matrixB : null,
        rowsB: this.needsTwoMatrices ? this.rowsB : null,
        colsB: this.needsTwoMatrices ? this.colsB : null
      };
      
      try {
    const { data } = await this.$http({
      url: this.$http.adornUrl("/matrix/calculate"),
      method: "post",
      data: this.$http.adornData({
        operation: this.selectedOperation,
        matrixA: this.matrixA,
        matrixB: this.needsTwoMatrices ? this.matrixB : undefined
      }, false),
    });
    
    if (data.success) {
          if (data.result && data.result.matrix) {
            this.resultMatrix = data.result.matrix;
            this.scalarResult = null;
          } else if (data.result) {
            this.scalarResult = data.result.value;
            this.resultMatrix = null;
          }
          
          // 添加到历史记录
          this.history.unshift({
            operation: this.getOperationName(this.selectedOperation),
            expression: this.getExpressionString(),
            result: this.getResultString(),
            data: JSON.parse(JSON.stringify(requestData))
          });
    } else {
      this.errorMessage = '计算错误: ' + (data.error || '未知错误');
      this.clearResult();
    }
  } catch (error) {
    this.errorMessage = '请求错误: ' + error.message;
    this.clearResult();
  }
    },
    
    clearResult() {
      this.resultMatrix = null;
      this.scalarResult = null;
      // 不清除errorMessage，让用户看到错误信息
    },
    
    getOperationName(op) {
      const names = {
        add: '矩阵加法',
        subtract: '矩阵减法',
        multiply: '矩阵乘法',
        transpose: '矩阵转置',
        determinant: '行列式',
        inverse: '矩阵求逆'
      };
      return names[op] || op;
    },
    
    getExpressionString() {
      if (this.selectedOperation === 'transpose') {
        return 'transpose(A)';
      } else if (this.selectedOperation === 'determinant') {
        return 'det(A)';
      } else if (this.selectedOperation === 'inverse') {
        return 'A⁻¹';
      } else {
        return `A ${this.selectedOperation === 'add' ? '+' : 
                this.selectedOperation === 'subtract' ? '-' : '×'} B`;
      }
    },
    
    getResultString() {
      if (this.scalarResult !== null) {
        return this.formatNumber(this.scalarResult);
      } else if (this.resultMatrix) {
        return this.resultMatrix.map(row => 
          `[${row.map(num => this.formatNumber(num)).join(', ')}]`
        ).join('\n');
      }
      return '';
    },
    
    useHistory(item) {
      this.selectedOperation = item.data.operation;
      this.rowsA = item.data.rowsA;
      this.colsA = item.data.colsA;
      this.matrixA = item.data.matrixA;
      
      if (item.data.matrixB) {
        this.rowsB = item.data.rowsB;
        this.colsB = item.data.colsB;
        this.matrixB = item.data.matrixB;
      }
      
      if (item.data.result && item.data.result.matrix) {
        this.resultMatrix = item.data.result.matrix;
        this.scalarResult = null;
      } else if (item.data.result) {
        this.scalarResult = item.data.result.value;
        this.resultMatrix = null;
      } else {
        this.scalarResult = null;
        this.resultMatrix = null;
      }
    }
  }
};
</script>

<style scoped>
.matrix-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}
.error-message {
  margin: 15px 0;
  width: 100%;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}
.matrix-input, .matrix-result {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
  min-width: 250px;
}

.matrix-dimension-controls {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.matrix-grid {
  overflow-x: auto;
}

.matrix-row {
  display: flex;
  justify-content: center;
  margin-bottom: 5px;
}

.matrix-row:last-child {
  margin-bottom: 0;
}

.matrix-cell {
  width: 60px;
  padding: 5px;
  margin: 2px;
  text-align: center;
  border: 1px solid #eee;
  background-color: white;
}

.result-display {
  background-color: white;
  padding: 10px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.scalar-result {
  font-size: 1.2em;
  font-weight: bold;
  text-align: center;
  margin-top: 10px;
  padding: 10px;
  background-color: white;
  border-radius: 4px;
}

.el-header {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #dcdfe6;
  padding: 0 20px;
}

.el-footer {
  border-top: 1px solid #dcdfe6;
  margin-top: 20px;
  padding: 20px;
}

/* 调整输入框样式 */
.matrix-dimension-controls .el-input-number {
  line-height: 28px;
}

.matrix-dimension-controls .el-input-number__decrease,
.matrix-dimension-controls .el-input-number__increase {
  width: 20px;
  line-height: 14px;
}
</style>